/**
 * Created by Ysssssss on 20/12/15.
 */
const app = getApp();
import { formatPrice } from "../../../common/utils";
import { tipToast, navBack } from '../../../common/env';

Page({
    data: {
        standardList: [],
        standardErrorMap: {},
        batchEditPriceModalVisible: false,
        _properties: []
    },

    onLoad() {
        const eventChannel = this.getOpenerEventChannel()
        eventChannel.on('acceptDataFromOpenerPage', (data) => {
            const { standardList, properties } = data
            this.setData({
                standardList,
                _properties: properties
            })
        })
    },

    // 批量设置价格弹窗显示
    showBatchEditPriceModal() {
        this.setData({
            batchEditPriceModalVisible: true
        })
    },

    // 批量改价confirm
    setAllStandardPrice(e) {
        const { standardList } = this.data
        const value = e.detail
        if (value === '') {
            tipToast('请输入价格')
        } else if (isNaN(value)) {
            tipToast('价格格式不正确')
        } else {
            this.setData({
                standardList: standardList.map(standard => ({
                    ...standard,
                    price: formatPrice(value)
                })),
                batchEditPriceModalVisible: false
            })
        }
    },
    // 批量改价弹窗close
    closeEditModal(e) {
        if (e.detail !== 'confirm') {
            this.setData({
                batchEditPriceModalVisible: false
            })
        }
    },

    handleStandardChange (e) {
        const { standardList } = this.data
        const { index } = e.currentTarget.dataset
        this.setData({
            standardList: [
                ...standardList.slice(0, index),
                e.detail,
                ...standardList.slice(index + 1)
            ]
        })
    },

    submitSkuInfo () {
        const { standardList, _properties } = this.data
        let standardErrorMap = {}
        let errorMessage = ''
        standardList.forEach(standard => {
            const { id, price } = standard
            standardErrorMap[id] = (price === '' || isNaN(price))
            if (errorMessage) return;
            if (price === '') {
                errorMessage = '请输入价格'
            } else if (isNaN(price)) {
                errorMessage = '价格格式不正确'
            }
        })
        if (errorMessage) {
            this.setData({
                standardErrorMap
            })
            tipToast(errorMessage)
        } else {
            app.event.trigger('productSkusChange', {
                standardList,
                properties: _properties
            })
            navBack(2)
        }
    }
})